#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/config/functions"
source "$PLUGIN_AVAILABLE_PATH/ps/functions"

trigger-scheduler-docker-local-scheduler-run() {
  declare desc="runs command in container based on app image"
  declare trigger="scheduler-run"
  declare DOKKU_SCHEDULER="$1" APP="$2" ENV_COUNT="$3"
  local CONTAINER_ID
  shift 3

  declare RUN_ENV=("${@:1:ENV_COUNT}")
  shift "$ENV_COUNT"

  if [[ "$DOKKU_SCHEDULER" != "docker-local" ]]; then
    return
  fi

  local DOCKER_RUN_LABEL_ARGS="--label=com.dokku.app-name=$APP"
  local IMAGE_TAG=$(get_running_image_tag "$APP")
  local IMAGE=$(get_deploying_app_image_name "$APP" "$IMAGE_TAG")

  if [[ -z "$DOKKU_RM_CONTAINER" ]]; then
    local DOKKU_APP_RM_CONTAINER=$(config_get "$APP" DOKKU_RM_CONTAINER || true)
    local DOKKU_GLOBAL_RM_CONTAINER=$(config_get --global DOKKU_RM_CONTAINER || true)
    local DOKKU_RM_CONTAINER=${DOKKU_APP_RM_CONTAINER:="$DOKKU_GLOBAL_RM_CONTAINER"}
  fi

  local DOCKER_ARGS=$(: | plugn trigger docker-args-run "$APP" "$IMAGE_TAG")
  [[ "$DOKKU_TRACE" ]] && DOCKER_ARGS+=" -e TRACE=true "

  local DYNO_NUMBER="$RANDOM"
  local IMAGE_SOURCE_TYPE="dockerfile"
  is_image_herokuish_based "$IMAGE" "$APP" && IMAGE_SOURCE_TYPE="herokuish"
  DOCKER_ARGS+=$(: | plugn trigger docker-args-process-run "$APP" "$IMAGE_SOURCE_TYPE" "$IMAGE_TAG")
  DOCKER_ARGS+=" -e DYNO=run.$DYNO_NUMBER --name $APP.run.$DYNO_NUMBER"

  declare -a ARG_ARRAY
  eval "ARG_ARRAY=($DOCKER_ARGS)"

  if [[ "$DOKKU_RM_CONTAINER" ]]; then
    DOCKER_ARGS+=" --rm"
  fi
  has_tty && DOCKER_ARGS+=" --interactive --tty"
  # the output of docker-args-run is possibly quoted/escaped so eval to normalize
  declare -a DOCKER_ARGS_ARRAY
  eval "DOCKER_ARGS_ARRAY=($DOCKER_ARGS)"
  for env_pair in "${RUN_ENV[@]}"; do
    DOCKER_ARGS_ARRAY+=("--env=$env_pair")
  done

  if [[ -n "$DOKKU_GLOBAL_FLAGS" ]]; then
    read -ra flags <<<"$DOKKU_GLOBAL_FLAGS"
    for flag in "${flags[@]}"; do
      if [[ "$flag" =~ ^--label.* ]]; then
        DOCKER_ARGS_ARRAY+=("$flag")
      fi
    done
  fi

  [[ "$IMAGE_SOURCE_TYPE" == "herokuish" ]] && local EXEC_CMD="/exec"

  DOKKU_QUIET_OUTPUT=1 extract_procfile "$APP"

  POTENTIAL_PROCFILE_KEY="$1"
  PROC_CMD=$(get_cmd_from_procfile "$APP" "$POTENTIAL_PROCFILE_KEY" 2>/dev/null || echo '')
  remove_procfile "$APP"

  if [[ -n "$PROC_CMD" ]]; then
    dokku_log_info1_quiet "Found '$POTENTIAL_PROCFILE_KEY' in Procfile, running that command"
    set -- "$PROC_CMD" "${@:2}"
  fi

  # shellcheck disable=SC2086
  CONTAINER_ID="$("$DOCKER_BIN" container create --label=com.dokku.container-type=run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS "${DOCKER_ARGS_ARRAY[@]}" $IMAGE $EXEC_CMD "$@")"
  plugn trigger post-container-create "app" "$CONTAINER_ID" "$APP" "run"

  declare -a DOCKER_START_ARGS_ARRAY
  if [[ "$DOKKU_DETACH_CONTAINER" != "1" ]]; then
    DOCKER_START_ARGS_ARRAY+=("--attach")

    has_tty && DOCKER_START_ARGS_ARRAY+=" --interactive"
  fi

  local EXIT_CODE=0 DOKKU_CONTAINER_EXIT_CODE=0
  if [[ "$DOKKU_DETACH_CONTAINER" == "1" ]]; then
    "$DOCKER_BIN" container start ${DOCKER_START_ARGS_ARRAY[@]} "$CONTAINER_ID" >/dev/null || DOKKU_CONTAINER_EXIT_CODE=$?
    echo "$CONTAINER_ID"
  else
    "$DOCKER_BIN" container start ${DOCKER_START_ARGS_ARRAY[@]} "$CONTAINER_ID" || EXIT_CODE=$?
    DOKKU_CONTAINER_EXIT_CODE="$("$DOCKER_BIN" container wait "$CONTAINER_ID" 2>/dev/null || echo "$EXIT_CODE")"
    [[ -z "$DOKKU_CONTAINER_EXIT_CODE" ]] && DOKKU_CONTAINER_EXIT_CODE=0
  fi
  plugn trigger scheduler-post-run "$DOKKU_SCHEDULER" "$APP" "$CONTAINER_ID" "$DOKKU_CONTAINER_EXIT_CODE"
  return "$DOKKU_CONTAINER_EXIT_CODE"
}

trigger-scheduler-docker-local-scheduler-run "$@"
